﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VehicleMaintenance.Framework;
using VehicleMaintenance.Models;
using System.Windows.Forms.DataVisualization.Charting;

namespace VehicleMaintenance.Query
{
    public partial class CashAccountsForm : BaseForm
    {
        private class ChartData
        {
            public int goodID;
            public string goodName;
            public int number;
            public decimal Amount;
            public string date;
            public string unit;
        }

        private List<ChartData> saleList;
        private List<ChartData> buyList;

        public CashAccountsForm()
        {
            InitializeComponent();
        }

        private void CashAccountsForm_Load(object sender, EventArgs e)
        {
            try
            {
                DataBindForSales();
                DataBindForBuy();

                rbIncome.Checked = true;
            }
            catch (Exception ex)
            {

                this.ShowInfo(ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            try
            {
                this.Close();
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void DataBindForSales()
        {
            try
            {
                lvIncome.Groups.Clear();
                lvIncome.Items.Clear();

                saleList = new List<ChartData>();
                buyList = new List<ChartData>();

                int number = 0;
                decimal totalPrice = 0;
                decimal offerAmount = 0;

                CarDBContext db = new CarDBContext();
                string strFrom = dtpFrom.Value.ToString("yyyy年MM月dd日");
                string strTo = dtpTo.Value.ToString("yyyy年MM月dd日");
                var list = db.RecipientsBill.Include("Good").Where(p => p.IsSettle == 1 && p.Date.CompareTo(strFrom) >= 0 && p.Date.CompareTo(strTo) <= 0).OrderBy(p => p.Date);
                ListViewGroup lvGroup = new ListViewGroup();
                if (list != null)
                {

                    lvGroup.Header = "维修收入";
                    foreach (var item in list)
                    {
                        ListViewItem lv = new ListViewItem(new string[]{item.Code,item.Good.Code,item.Good.Name,item.Number.ToString(),
													item.UnitPrice.ToString(),item.OfferAmount.ToString(),item.TotalPrice.ToString(),
													item.Date,item.Remark});
                        lvGroup.Items.Add(lv);
                        lvIncome.Items.Add(lv);
                        number += item.Number;
                        totalPrice += item.TotalPrice;
                        offerAmount += item.OfferAmount;

                        ChartData data = new ChartData();
                        data.goodID = item.GoodID;
                        data.goodName = item.Good.Name;
                        data.number = item.Number;
                        data.Amount = item.TotalPrice;
                        data.date = item.Date;
                        data.unit = item.Units;
                        saleList.Add(data);

                    }
                    lvIncome.Groups.Add(lvGroup);
                }
                var list2 = db.SalesBill.Include("Good").Where(p => p.IsSettle == "是" && p.Date.CompareTo(strFrom) >= 0 && p.Date.CompareTo(strTo) <= 0).OrderBy(p => p.Date);
                if (list2 != null)
                {
                    lvGroup = new ListViewGroup();
                    lvGroup.Header = "销售收入";
                    foreach (var item in list2)
                    {
                        ListViewItem lv = new ListViewItem(new string[]{item.Code,item.Good.Code,item.Good.Name,item.Number.ToString(),
													item.UnitPrice.ToString(),item.OfferAmount.ToString(),item.TotalPrice.ToString(),
													item.Date,item.Remark});
                        lvGroup.Items.Add(lv);
                        lvIncome.Items.Add(lv);
                        number += item.Number;
                        totalPrice += item.TotalPrice;
                        offerAmount += item.OfferAmount;

                        ChartData data = new ChartData();
                        data.goodID = item.GoodID;
                        data.goodName = item.Good.Name;
                        data.number = item.Number;
                        data.Amount = item.TotalPrice;
                        data.date = item.Date;
                        data.unit = item.Units;
                        saleList.Add(data);

                    }
                    lvIncome.Groups.Add(lvGroup);
                }
                var list3 = db.PurchaseReturnsBill.Include("Good").Where(p => p.Date.CompareTo(strFrom) >= 0 && p.Date.CompareTo(strTo) <= 0).OrderBy(p => p.Date);
                if (list3 != null)
                {
                    lvGroup = new ListViewGroup();
                    lvGroup.Header = "库存退货收入";
                    foreach (var item in list3)
                    {
                        ListViewItem lv = new ListViewItem(new string[]{item.Code,item.Good.Code,item.Good.Name,item.Number.ToString(),
													item.ReturnValue.ToString(),(item.ReturnValue -item.PurchasePrice).ToString(),item.ReturnPrice.ToString(),
													item.Date,item.Remark});
                        lvGroup.Items.Add(lv);
                        lvIncome.Items.Add(lv);
                        number += item.Number;
                        totalPrice += item.ReturnPrice;
                        offerAmount += (item.ReturnValue - item.PurchasePrice);

                        ChartData data = new ChartData();
                        data.goodID = item.GoodID;
                        data.goodName = item.Good.Name;
                        data.number = item.Number;
                        data.Amount = item.ReturnPrice;
                        data.date = item.Date;
                        data.unit = item.Units;
                        saleList.Add(data);

                    }
                    lvIncome.Groups.Add(lvGroup);
                }
                if (lvIncome.Items.Count > 0)
                {
                    lvGroup = new ListViewGroup();
                    lvGroup.Header = "合计";
                    ListViewItem lv = new ListViewItem(new string[] { "", "", "", number.ToString(), "", offerAmount.ToString("f1"), totalPrice.ToString("f1"), "", "" });
                    lvGroup.Items.Add(lv);
                    lvIncome.Items.Add(lv);

                    lvIncome.Groups.Add(lvGroup);
                }
                SetListViewItemColor(lvIncome);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private void DataBindForBuy()
        {
            try
            {
                lvExpenditure.Groups.Clear();
                lvExpenditure.Items.Clear();

                int number = 0;
                decimal totalPrice = 0;
                decimal offerAmount = 0;

                CarDBContext db = new CarDBContext();
                string strFrom = dtpFrom.Value.ToString("yyyy年MM月dd日");
                string strTo = dtpTo.Value.ToString("yyyy年MM月dd日");
                var list = db.PurchaseBill.Include("Good").Where(p => p.IsSettle == "是" && p.Date.CompareTo(strFrom) >= 0 && p.Date.CompareTo(strTo) <= 0).OrderBy(p => p.Date);
                if (list != null)
                {
                    ListViewGroup lvGroup = new ListViewGroup();
                    lvGroup.Header = "进货支出";
                    foreach (var item in list)
                    {
                        ListViewItem lv = new ListViewItem(new string[]{item.Code,item.Good.Code,item.Good.Name,item.Number.ToString(),
													item.PurchasePrice.ToString(),item.OfferAmount.ToString(),item.TotalPrice.ToString(),
													item.Date,item.Remark});
                        lvGroup.Items.Add(lv);
                        lvExpenditure.Items.Add(lv);
                        number += item.Number;
                        totalPrice += item.TotalPrice;
                        offerAmount += item.OfferAmount;

                        ChartData data = new ChartData();
                        data.goodID = item.GoodID;
                        data.goodName = item.Good.Name;
                        data.number = item.Number;
                        data.Amount = item.TotalPrice;
                        data.date = item.Date;
                        data.unit = item.Units;
                        buyList.Add(data);

                    }
                    lvExpenditure.Groups.Add(lvGroup);
                }
                var list2 = db.SalesReturnsBill.Include("Good").Where(p => p.Date.CompareTo(strFrom) >= 0 && p.Date.CompareTo(strTo) <= 0).OrderBy(p => p.Date);
                if (list2 != null)
                {
                    ListViewGroup lvGroup = new ListViewGroup();
                    lvGroup.Header = "销售退货支出";
                    foreach (var item in list2)
                    {
                        ListViewItem lv = new ListViewItem(new string[]{item.Code,item.Good.Code,item.Good.Name,item.Number.ToString(),
													item.ReturnValue.ToString(),(item.ReturnValue - item.PurchasePrice).ToString(),item.ReturnPrice.ToString(),
													item.Date,item.Remark});
                        lvGroup.Items.Add(lv);
                        lvExpenditure.Items.Add(lv);
                        number += item.Number;
                        totalPrice += item.ReturnPrice;
                        offerAmount += (item.ReturnValue - item.PurchasePrice);

                        ChartData data = new ChartData();
                        data.goodID = item.GoodID;
                        data.goodName = item.Good.Name;
                        data.number = item.Number;
                        data.Amount = item.ReturnPrice;
                        data.date = item.Date;
                        data.unit = item.Units;
                        buyList.Add(data);

                    }
                    lvExpenditure.Groups.Add(lvGroup);
                }
                if (lvExpenditure.Items.Count > 0)
                {
                    ListViewGroup lvGroup = new ListViewGroup();
                    lvGroup.Header = "合计";
                    ListViewItem lv = new ListViewItem(new string[] { "", "", "", number.ToString(), "", offerAmount.ToString("f1"), totalPrice.ToString("f1"), "", "" });
                    lvGroup.Items.Add(lv);
                    lvExpenditure.Items.Add(lv);

                    lvExpenditure.Groups.Add(lvGroup);
                }
                SetListViewItemColor(lvExpenditure);
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        private void SetListViewItemColor(ListView lv)
        {
            if (lv.Items.Count > 0)
            {
                foreach (ListViewItem item in lv.Items)
                {
                    if (item.Index % 2 == 0)
                    {
                        item.BackColor = Color.WhiteSmoke;
                    }
                }
            }
        }

        private void dtpFrom_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dtpFrom.Text.CompareTo(dtpTo.Text) > 0)
                {
                    this.ShowInfo("开始日期不能大于结束日期");
                    dtpFrom.Value = dtpTo.Value;
                    return;
                }

                DataBindForSales();

                DataBindForBuy();

                rbIncome_CheckedChanged(sender, e);
                rbExpenditure_CheckedChanged(sender, e);
                rbProfit_CheckedChanged(sender, e);

            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void dtpTo_ValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (dtpTo.Text.CompareTo(dtpFrom.Text) < 0)
                {
                    this.ShowInfo("结束日期不能小于开始日期");
                    dtpTo.Value = dtpFrom.Value;
                    return;
                }

                DataBindForSales();

                DataBindForBuy();

                rbIncome_CheckedChanged(sender, e);
                rbExpenditure_CheckedChanged(sender, e);
                rbProfit_CheckedChanged(sender, e);
            }
            catch (Exception ex)
            {
                this.ShowInfo(ex.Message);
            }
        }

        private void rbAll_CheckedChanged(object sender, EventArgs e)
        {
            if (rbAll.Checked)
            {
                dtpFrom.Value = DateTime.Parse("2011-01-01");
                dtpTo.Value = DateTime.Now;
            }
        }

        private void rbDay_CheckedChanged(object sender, EventArgs e)
        {
            if (rbDay.Checked)
            {
                dtpFrom.Value = DateTime.Now;
                dtpTo.Value = DateTime.Now;
            }
        }

        private void rbWeek_CheckedChanged(object sender, EventArgs e)
        {
            if (rbWeek.Checked)
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
                {
                    dtpFrom.Value = DateTime.Now.AddDays(-6);
                }
                else
                {
                    dtpFrom.Value = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfWeek - 1));
                }
                dtpTo.Value = DateTime.Now;
            }
        }

        private void rbMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (rbMonth.Checked)
            {
                dtpFrom.Value = DateTime.Now.AddDays(-((int)DateTime.Now.Day - 1));
                dtpTo.Value = DateTime.Now;
            }
        }

        private void rbYear_CheckedChanged(object sender, EventArgs e)
        {
            if (rbYear.Checked)
            {
                dtpFrom.Value = DateTime.Now.AddDays(-((int)DateTime.Now.DayOfYear - 1));
                dtpTo.Value = DateTime.Now;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                rbIncome.Checked = true;
            }
            else if (tabControl1.SelectedIndex == 1)
            {
                rbExpenditure.Checked = true;
            }
        }

        private void rbIncome_CheckedChanged(object sender, EventArgs e)
        {
            if (rbIncome.Checked)
            {
                ChartDisplay(saleList);

                decimal tot = 0M;
                if (saleList != null)
                {
                    foreach (var item in saleList)
                    {
                        tot += item.Amount;
                    }
                }
                lbTotal.Text = tot.ToString("f1");
            }
        }

        private void rbExpenditure_CheckedChanged(object sender, EventArgs e)
        {
            if (rbExpenditure.Checked)
            {
                ChartDisplay(buyList);

                decimal tot = 0M;
                if (saleList != null)
                {
                    foreach (var item in buyList)
                    {
                        tot += item.Amount;
                    }
                }
                lbTotal.Text = tot.ToString("f1");
            }
        }


        private void rbProfit_CheckedChanged(object sender, EventArgs e)
        {
            if (rbProfit.Checked)
            {
                ChartDisplayForProfit();
            }
        }

        private void ChartDisplayForProfit()
        {
            string str2 = "";
            if (dtpFrom.Value.ToString("yyyyMMdd") == dtpTo.Value.ToString("yyyyMMdd"))
            {
                str2 = dtpFrom.Text;
            }
            else
            {
                str2 = dtpFrom.Text + "--" + dtpTo.Text;
            }

            string str = "";
            if (rbProfit.Checked)
            {
                str = "利润";
            }
            chart1.Titles[0].Text = string.Format("{0}--{1}统计图", str2, str);

            chart1.ChartAreas.Clear();
            ChartArea chartArea = new ChartArea();
            chartArea.Axes[1].Title = "金额/元";
            chartArea.Axes[1].TitleAlignment = StringAlignment.Far;
            chartArea.Axes[1].TextOrientation = TextOrientation.Stacked;
            chart1.ChartAreas.Add(chartArea);
            chart1.Series.Clear();

            Series series = new Series();
            series.ChartArea = chart1.ChartAreas[0].Name;
            series.Legend = chart1.Legends[0].Name;
            series.Name = "销售收入";
            chart1.Series.Add(series);

            Series series2 = new Series();
            series2.ChartArea = chart1.ChartAreas[0].Name;
            series2.Legend = chart1.Legends[0].Name;
            series2.Name = "购买支出";
            chart1.Series.Add(series2);

            Series series3 = new Series();
            series3.ChartArea = chart1.ChartAreas[0].Name;
            series3.Legend = chart1.Legends[0].Name;
            series3.Name = "当月其他支出";
            chart1.Series.Add(series3);

            decimal tot = 0M;

            //销售收入
            int num = 0;
            decimal total = 0M;
            string tip = "";
            foreach (var item in saleList)
            {
                num += item.number;
                total += item.Amount;
                tip += string.Format("{0}:{1}{2},{3}元;\r\n", item.goodName, item.number, item.unit, item.Amount);
                tot += item.Amount;
            }
            chart1.Series["销售收入"].Points.AddXY("", total);
            chart1.Series["销售收入"].Points[chart1.Series["销售收入"].Points.Count - 1].Label = total.ToString() + "元";
            chart1.Series["销售收入"].Points[chart1.Series["销售收入"].Points.Count - 1].ToolTip = tip;
            chart1.Series["销售收入"].Points[chart1.Series["销售收入"].Points.Count - 1].LabelToolTip = "销售收入";

            //购买支出
            num = 0;
            total = 0M;
            tip = "";
            foreach (var item in buyList)
            {
                num += item.number;
                total += item.Amount;
                tip += string.Format("{0}:{1}{2},{3}元;\r\n", item.goodName, item.number, item.unit, item.Amount);
                tot -= item.Amount;
            }
            chart1.Series["购买支出"].Points.AddXY("", -total);
            chart1.Series["购买支出"].Points[chart1.Series["购买支出"].Points.Count - 1].Label = total.ToString() + "元";
            chart1.Series["购买支出"].Points[chart1.Series["购买支出"].Points.Count - 1].ToolTip = tip;
            chart1.Series["购买支出"].Points[chart1.Series["购买支出"].Points.Count - 1].LabelToolTip = "购买支出";

            //当月其他支出
            CarDBContext db = new CarDBContext();
            string date = DateTime.Now.ToString("yyyy-MM");
            if (dtpFrom.Value.ToString("yyyy-MM") == dtpTo.Value.ToString("yyyy-MM"))
            {
                date = dtpFrom.Value.ToString("yyyy-MM");
            }
            var expenditure = db.OtherExpenditure.Where(p => p.Date == date);
            total = 0M;
            tip = "";
            if (expenditure != null)
            {
                foreach (var item in expenditure)
                {
                    total += item.Amount;
                    tip += string.Format("{0}:{1}元;\r\n", item.Type,item.Amount);
                    tot -= item.Amount;
                }
            }

            chart1.Series["当月其他支出"].Points.AddXY("", -total);
            chart1.Series["当月其他支出"].Points[chart1.Series["当月其他支出"].Points.Count - 1].Label = total.ToString() + "元";
            chart1.Series["当月其他支出"].Points[chart1.Series["当月其他支出"].Points.Count - 1].ToolTip = tip;
            chart1.Series["当月其他支出"].Points[chart1.Series["当月其他支出"].Points.Count - 1].LabelToolTip = "当月其他支出";

            lbTotal.Text = tot.ToString("f1");
        }

        private void ChartDisplay(List<ChartData> list)
        {
            chart1.ChartAreas.Clear();
            ChartArea chartArea = new ChartArea();
            chartArea.Axes[1].Title = "金额/元";
            chartArea.Axes[1].TitleAlignment = StringAlignment.Far;
            chartArea.Axes[1].TextOrientation = TextOrientation.Stacked;
            chart1.ChartAreas.Add(chartArea);
            chart1.Series.Clear();
            CarDBContext db = new CarDBContext();

            string str2 = "";
            if (dtpFrom.Value.ToString("yyyyMMdd") == dtpTo.Value.ToString("yyyyMMdd"))
            {
                var goods = db.Goods;
                foreach (var good in goods)
                {
                    Series series = new Series();
                    series.ChartArea = chart1.ChartAreas[0].Name;
                    series.Legend = chart1.Legends[0].Name;
                    series.Name = good.Name;
                    chart1.Series.Add(series);
                }
                str2 = dtpFrom.Text;
            }
            else
            {
                str2 = dtpFrom.Text + "--" + dtpTo.Text;
            }

            string str = "";
            if (rbIncome.Checked)
            {
                str = "收入";
            }
            else if (rbExpenditure.Checked)
            {
                str = "支出";
            }
            chart1.Titles[0].Text = string.Format("{0}--{1}统计图", str2, str);


            for (DateTime d = dtpFrom.Value; d.ToString("yyyyMMdd").CompareTo(dtpTo.Value.ToString("yyyyMMdd")) <= 0; d = d.AddDays(1))
            {
                string date = d.ToString("yyyy年MM月dd日");
                var item = list.Where(p => p.date == date);
                if (dtpFrom.Value.ToString("yyyyMMdd") == dtpTo.Value.ToString("yyyyMMdd"))
                {
                    var goods = db.Goods;
                    foreach (var t in goods)
                    {
                        var g = item.Where(p => p.goodID == t.GoodID);
                        int num = 0;
                        decimal tot = 0.0M;
                        foreach (var j in g)
                        {
                            num += j.number;
                            tot += j.Amount;
                        }
                        chart1.Series[t.Name].Points.AddXY(date, tot);
                        chart1.Series[t.Name].Points[chart1.Series[t.Name].Points.Count - 1].Label = tot.ToString() + "元";
                        chart1.Series[t.Name].Points[chart1.Series[t.Name].Points.Count - 1].ToolTip = string.Format("{0}{1},零售价{2}元", num, t.Units, t.RetailPrice);
                        chart1.Series[t.Name].Points[chart1.Series[t.Name].Points.Count - 1].LabelToolTip = t.Name;
                    }
                }
                else
                {
                    if (chart1.Series.Count == 0)
                    {
                        Series series = new Series();
                        series.Name = "金额";
                        chart1.Series.Add(series);
                    }
                    string tip = "";
                    int num = 0;
                    decimal tot = 0.0M;
                    foreach (var g in item)
                    {
                        num += g.number;
                        tot += g.Amount;
                        tip += string.Format("{0}:{1}{2},{3}元;\r\n", g.goodName, g.number, g.unit, g.Amount);
                    }
                    chart1.Series[0].Points.AddXY(date, tot);
                    chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].Label = tot.ToString() + "元";
                    chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].LabelToolTip = date;
                    chart1.Series[0].Points[chart1.Series[0].Points.Count - 1].ToolTip = tip;
                }
            }
        }

    }
}
